<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.categoryName" placeholder="类别" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleSearch"
      />
      <el-input v-model="listQuery.tagName" placeholder="标签" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleSearch"
      />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleSearch">
        查询
      </el-button>
      <el-checkbox v-model="showCategory" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        显示所属类别
      </el-checkbox>
      <el-checkbox v-model="showComment" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        显示备注
      </el-checkbox>

      <el-button style="float: right" v-waves :loading="downloadLoading" class="filter-item" type="success" disabled
                 icon="el-icon-download"
                 @click="handleDownload"
      >
        导出(开发中)
      </el-button>



    </div>
    <div style="margin-top: 15px; ">

      <el-input placeholder="请输入标签名称" v-model="addingTag.inputTagName" class="input-with-select"
                @keyup.enter.native="addClassifiedTag"
      >
        <el-select class="category-searchable-select" style="width: 20%" v-model="addingTag.selectedCategoryId"
                   :remote-method="getRemoteCategoryList"
                   @focus="getRemoteCategoryList"
                   slot="prepend" placeholder="请选择类别"
                   filterable default-first-option remote
        >
          <el-option label="不指定类别" value="-1"></el-option>
          <el-option v-for="(item,index) in addingTag.categoryOptions" :key="item.id" :label="item.name"
                     :value="item.id"
          />
        </el-select>
        <el-button slot="append" icon="el-icon-finished" @click="addClassifiedTag">
          点击此处或敲击回车键进行添加
        </el-button>
      </el-input>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="编号" prop="id" sortable="custom" align="center" min-width="80"
                       :class-name="getSortClass('id')"
      >
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标签" align="center" min-width="150">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="showCategory" label="所属类别" min-width="300" align="center">
        <template slot-scope="{row}">
          <span>{{ row.categories.map(category => category.name).join(', ') }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="showComment" label="备注" min-width="200" align="center">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-input v-model="row.comment" class="edit-input" size="small"/>
            <el-button
              class="cancel-btn"
              size="small"
              icon="el-icon-refresh"
              type="warning"
              @click="cancelEditComment(row)"
            >
              取消
            </el-button>
          </template>
          <span v-else>{{ row.comment }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" min-width="100" align="center">
        <template slot-scope="{row}">
          <span>{{ row.creator }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" min-width="150" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" min-width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button
            v-if="showComment&&row.edit"
            type="success"
            size="mini"
            icon="el-icon-circle-check-outline"
            @click="confirmEditComment(row)"
          >
            确认修改
          </el-button>
          <el-button
            v-else-if="showComment&&!row.edit"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="row.edit=!row.edit"
          >
            备注
          </el-button>
          <el-button type="primary" size="mini" @click="handleClickTagDetail(row)">
            详情
          </el-button>

          <el-popconfirm
            confirmButtonText="确定"
            cancelButtonText="取消"
            icon="el-icon-info"
            iconColor="red"
            title="确定删除吗？"
            @onConfirm="deleteTag(row)"
          >
            <el-button style="margin-left: 10px" slot="reference" type="danger" size="mini">
              删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"
    />

    <TagDetailDialog :tag-id="tagDetailDialog.currentTagId"
                     :visible="tagDetailDialog.visible"
                     :tag-name="tagDetailDialog.currentTagName"
                     @tagDetailDialogClose="handleTagDetailDialogClose"
    />

  </div>


</template>

<script>
import { addTagByCategoryId, fetchTagList, findCategories, deleteTagById, updateCommentByTagId } from '@/api/tag'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import TagDetailDialog from '@/views/tag/TagDetailDialog.vue'
import { string } from 'jszip/lib/support'

export default {
  name: 'CategoryList',
  components: { TagDetailDialog, Pagination },
  directives: { waves },
  filters: {},
  data() {
    return {
      showComment: false,
      showCategory: false,
      addingTag: {
        inputTagName: '',
        selectedCategoryId: '-1',
        categoryOptions: []
      },

      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        categoryName: null,
        tagName: null,
        creatorName: null,
        sort: '-id'
      },

      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      tagDetailDialog: {
        visible: false,
        currentTagId: -1,
        currentTagName: ''
      },

      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },

  methods: {
    getList() {
      this.listLoading = true
      fetchTagList(this.listQuery).then(response => {
        this.list = response.data.records.map(v => {
          this.$set(v, 'edit', false) // https://vuejs.org/v2/guide/reactivity.html
          v.originalComment = v.comment //  will be used when user click the cancel botton
          return v
        })
        this.total = response.data.total

        this.listLoading = false
      })
    },
    cancelEditComment(row) {
      row.comment = row.originalComment
      row.edit = false
      this.$message({
        message: '备注未修改',
        type: 'warning'
      })
    },
    confirmEditComment(row) {
      row.edit = false
      row.originalComment = row.comment
      updateCommentByTagId(row.id, row.comment).then(response => {
        this.$message({
          message: response.message,
          type: 'success'
        })
      })
    },
    getRemoteCategoryList(categoryName) {
      // console.log(categoryName)
      //如果使用@focus，传入的参数是event

      if (!(categoryName instanceof String)) {
        categoryName = ''
      }
      findCategories(categoryName).then(response => {
        this.addingTag.categoryOptions = response.data
      })
    },
    handleClickTagDetail(row) {
      this.tagDetailDialog.currentTagId = row.id
      this.tagDetailDialog.currentTagName = row.name
      this.tagDetailDialog.visible = true
    },

    handleTagDetailDialogClose() {
      this.tagDetailDialog.visible = false
    },

    handleSearch() {
      this.listQuery.page = 1
      this.getList()
    },

    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      // this.handleSearch()
    },

    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    addClassifiedTag: function() {
      if (this.addingTag.inputTagName === null || this.addingTag.inputTagName.trim() === '') {
        return
      }
      addTagByCategoryId(this.addingTag.inputTagName, this.addingTag.selectedCategoryId).then(response => {
        this.addingTag.inputTagName = ''
        this.getList()
      })
    },
    deleteTag: function(row) {
      console.log('调用删除', row.id)
      deleteTagById(row.id).then(response => {
        this.$message.success(response.message)
        this.getList()
      })
    }
  }
}
</script>
<style>
.category-searchable-select .el-input {
  width: 198px;
}

.input-with-select .el-input-group__prepend {
  background-color: #ffffff;
}

.edit-input {
  padding-right: 100px;
}

.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
